/*
+--------------------------------------------------------------------------
|   Mblog [#RELEASE_VERSION#]
|   ========================================
|   Copyright (c) 2014, 2015 mtons. All Rights Reserved
|   http://www.mtons.com
|
+---------------------------------------------------------------------------
*/
package com.hefei.blog.web.controller.desk.account;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.hefei.blog.base.data.Data;
import com.hefei.blog.base.upload.consts.FileConsts;
import com.hefei.blog.base.utils.FileNameUtils;
import com.hefei.blog.base.utils.image.ImageHandleUtils;
import com.hefei.blog.core.persist.service.UserService;
import com.hefei.blog.web.consts.Views;
import com.hefei.blog.web.controller.BaseController;
import com.hefei.frontend.framework.http.request.CommonParameterThreadLocal;
import com.hefei.frontend.framework.http.request.RequestThreadLocal;

@Controller
@RequestMapping("/account")
public class AvatarController extends BaseController {
	
	private Logger logger = Logger.getLogger(AvatarController.class);
	
	@Autowired
	private UserService userService;

	@RequestMapping(value = "/avatar", method = RequestMethod.GET)
	public String view() {
		return getView(Views.ACCOUNT_AVATAR);
	}
	
	@RequestMapping(value = "/avatar", method = RequestMethod.POST)
	public String post(String path, Float x, Float y, Float width, Float height, ModelMap model,HttpServletRequest request,HttpServletResponse response) {
		if (StringUtils.isEmpty(path)) {
			model.put("data", Data.failure("请选择图片"));
			return getView(Views.ACCOUNT_AVATAR);
		}
		
		if (width != null && height != null) {
			try {
		        // 在目标目录下生成截图
		        String relativeScalePath = FileNameUtils.getFilename(path, String.valueOf(width.intValue()), "x");//f.getParent() + "/" + CommonParameterThreadLocal.getUserId() + ".jpg";
		        ImageHandleUtils.truncateImage(FileConsts.ROOT_PIC + path, FileConsts.ROOT_PIC + relativeScalePath, x.intValue(), y.intValue(), width.intValue());
		        
				// 对结果图片进行压缩
				String relativeDest =  FileNameUtils.getFilename(path, String.valueOf(100), "x");
		        ImageHandleUtils.scaleImage(FileConsts.ROOT_PIC + relativeScalePath, FileConsts.ROOT_PIC + relativeDest, 100);

				userService.updateAvatar(CommonParameterThreadLocal.getUserId(), relativeDest, request, response);
			} catch (Exception e) {
				logger.error(RequestThreadLocal.getTimer() + " error", e);
			}
		}
		return "redirect:/account/profile";
	}
}
